const request = require('request-promise')


const base = 'https://api.weixin.qq.com/cgi-bin/'
const api={
    accessToken:base+'token?grant_type=client_credential'

}

export default class WXserver{
    //构造一个微信的类
    constructor(ops){
        this.opts=Object.assign({},ops)
        this.appID=ops.appID
        this.appSecret=ops.appSecret
        this.getAccessToken = ops.getAccessToken
        this.saveAccessToken=ops.saveAccessToken
        this.fetchAccessToken()

        }

        
    
    // 发起一个请求
    async request (options){
        options = Object.assign({},options,{json:true})

        try {
            const response = await request(options)
            console.log(response)
            return response 
            
        } catch (error) {
            console.error(error)
        }
    }

    async fetchAccessToken(){
        let data = await this.getAccessToken()

        if(!this.isValidAccessToken(data)){
            data = await this.updateAccessToken()
        }
        await this.saveAccessToken(data)
       return data
    }

    async updateAccessToken(){
        const url = api.accessToken + '&appid=' + this.appID + '&secret='+this.appSecret
        const data = await this.request({url:url})
        const now = (new Date().getTime())
        const expiresIn = now + (data.expires_in - 20 ) *1000
        data.expires_in = expiresIn
        return data
    }

    isValidAccessToken(data){
        if (!data || !data.access_token || !data.expires_in){
            return false
        }
        
        const expiresIn = data.expires_in
        const now = (new Date().getTime())
        if (now < expiresIn){
            return true
        }else{
            return false
        }
    }
}